package com.sto.stoapp.activity.sales;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.activity.scanner.StoSelectTableActivity;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.dataprocess.ProcessScanCode;
import com.sto.stoapp.dataprocess.parcelable.GetTableParcel;
import com.sto.stoapp.dataprocess.parcelable.SelectTableParcel;
import com.sto.stoapp.db.StoDataBaseOperation;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.manager.SqlSelectTableManager;
import com.sto.stoapp.entity.BillPaymentEntity;
import com.sto.stoapp.entity.DataBusinessEntity;
import com.sto.stoapp.listener.StoOnClickListener;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.manager.SoundManager;
import com.sto.stoapp.status.EnumScanCode;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.thread.HelpGetPaymentThread;
import com.sto.stoapp.util.BillFilterUtil;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.widget.BaseDialog;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoHhmEditText.EditClickListener;
import com.sto.stoapp.widget.StoListenerActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressLint({ "HandlerLeak", "NewApi" })
public class SalesSignContentActivity extends StoListenerActivity {

	// private StoHhmEditText code;
	private StoHhmEditText autograph;
	private int title;
	private Button select;
	// private TextView ticketNumber, displayScanCode;

	private List<EditText> edit = new ArrayList<EditText>();

	private DataBusinessEntity dataBusiness;
	private String signName = "";

	private final int AUTOGRAPH_RESULT = 0xfe;

	private Handler mHandler=new Handler(){
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what){
				case HelpGetPaymentThread.MSG_WHAT:

					Helper.showWaitePaySound(SalesSignContentActivity.this);
					BillPaymentEntity entity= (BillPaymentEntity) msg.obj;

					ScanOff();
					final BaseDialog filterDialog=new BaseDialog(SalesSignContentActivity.this);
					filterDialog.setTitles("此单号【" + entity.getBillNo() + "】为代收货款单号，代收金额为：【￥"+Double.valueOf(entity.getBillPayment())+"】。请注意代收！");
					filterDialog.show();
					filterDialog.getvCanncel().setVisibility(View.GONE);
					filterDialog.getvAccept().setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							filterDialog.dismiss();
							ScanOpen();
						}
					});
					break;
			}

			super.handleMessage(msg);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sto_sales_sign_content);
		Bundle extras = getIntent().getExtras();
		title = extras.getInt("title");
		this.setTitleBottom(title, HomeBroadAction.SALES_MAN_BROAD);
		initPointLayout(true);
		initWidget();
		initListen();
		initScanListener();
		dataBusiness = new DataBusinessEntity();
		dataBusiness.initInsertData();
		initScanRecordAdapter(EnumTableNames.STATUS_TABLE_SALESMAN_SIGN);
	}

	private void initWidget() {
		code = (StoHhmEditText) this.findViewById(R.id.sign_odd_numbers_text);
		autograph = (StoHhmEditText) this.findViewById(R.id.autograph_text);
		// ticketNumber = (TextView) this.findViewById(R.id.sign_tickets_text);
		select = (Button) this.findViewById(R.id.select_autograph);
		// edit.add(autograph);
		// edit.add(code);
		addUploadTable(EnumTableNames.STATUS_TABLE_SALESMAN_SIGN);
		autograph.setInputType(InputType.TYPE_CLASS_TEXT);
	}

	/**
	 * 监听控件
	 */
	private void initListen() {

		autograph.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				onBackPressed();
			}

			@Override
			public void onEditClickListener(View v) {
				if (!autograph.getText().toString().isEmpty()) {
					code.requestFocus();
				} else {
					autograph.showSRF();
				}

			}
		});

		// autograph.setOnClickListener(new StoOnClickListener(this) {
		//
		// @Override
		// public void mHonClick(View v) {
		// if (!autograph.getText().toString().isEmpty()) {
		// code.requestFocus();
		// } else {
		// InputMethodManager inputManager =
		//
		// (InputMethodManager) autograph.getContext()
		// .getSystemService(Context.INPUT_METHOD_SERVICE);
		//
		// inputManager.showSoftInput(autograph, 0);
		// }
		// }
		// });

		/*
		 * autograph.setOnKeyListener(new StoOnKeyListener(this) {
		 * 
		 * @Override public boolean OnKeyListener(View view, int position,
		 * KeyEvent event) { if(position == event.KEYCODE_DEL){
		 * if(!autograph.getText().toString().isEmpty()){ autograph.setText("");
		 * return true; } else{ SalesSignContentActivity.this.finish(); } }
		 * return false; }
		 * 
		 * 
		 * });
		 */

		/*
		 * autograph.setOnLongClickListener(new OnLongClickListener() {
		 * 
		 * @Override public boolean onLongClick(View arg0) {
		 * if(autograph.getText().toString().isEmpty()){ SelectAutograph(); }
		 * return false; } });
		 */

		select.setOnClickListener(new StoOnClickListener(this) {

			@Override
			public void mHonClick(View v) {

				SelectAutograph();

			}
		});

		/*
		 * code.setOnClickListener(new StoOnClickListener(this) {
		 * 
		 * @Override public void mHonClick(View v) {
		 * onScanResults(code.getText().toString()); } });
		 */
		code.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				autograph.requestFocus();
				// autograph.selectAll();
			}

			@Override
			public void onEditClickListener(View v) {
				if (code.getText().toString().length() == 0) {
					Helper.showSoundToast(SalesSignContentActivity.this,
							getString(R.string.code_empty), false);
				} else {
					onScanResults(code.getText().toString());
				}
			}
		});

		/*
		 * code.setEditScanListener(new EditScanListener() {
		 * 
		 * @Override public void onScan() { ScanOpen(); }
		 * 
		 * @Override public void offScan() { ScanOff(); } });
		 */

		for (EditText editListener : edit) {
			/*
			 * 监听EditText控件焦点切换
			 */
			editListener.setOnFocusChangeListener(new OnFocusChangeListener() {

				@Override
				public void onFocusChange(View v, boolean hasFocus) {
					if (hasFocus) {

					}
				}
			});

			/*
			 * 监听EditText内容个数
			 */
			editListener.addTextChangedListener(new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start,
						int before, int count) {

				}

				@Override
				public void beforeTextChanged(CharSequence s, int start,
						int count, int after) {
				}

				@Override
				public void afterTextChanged(Editable s) {

				}
			});

		}

	}

	/**
	 * 选择签名
	 */
	private void SelectAutograph() {
		try {
			SelectTableParcel tableParcel = new SelectTableParcel();
			if (autograph.getText().length() == 0) {
				tableParcel
						.setSelectSql(SqlSelectTableManager.SQL_SIGN_INFO_ALL);
				tableParcel.setSelectField(new String[] {});
			} else {
				tableParcel
						.setSelectSql(SqlSelectTableManager.SQL_SIGN_INFO_LIKE);
				tableParcel.setSelectField(new String[] { "%"
						+ autograph.getText().toString() + "%" });
			}
			tableParcel.setSelectCode("shortKey");
			tableParcel.setSelectName("nameValue");

			Intent intent = new Intent(SalesSignContentActivity.this,
					StoSelectTableActivity.class);
			intent.putExtra("tableData", tableParcel);

			startActivityForResult(intent, AUTOGRAPH_RESULT);
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("SelectAutograph", e.getMessage());
		}
	}

	/**
	 * 扫描码判断
	 * 
	 * @param code
	 *            扫描码
	 * @return true/ok or false
	 */
	private boolean CheckScanCode(String code) {
		boolean ret = false;

		EnumScanCode status = ProcessScanCode.getInstance(this)
				.ScanCodeResolve(code,
						EnumTableNames.STATUS_TABLE_SALESMAN_SIGN);

		switch (status) {
		// 条码空
		case CODE_EMPTY:
			// Helper.showSoundToast(
			// SalesSignContentActivity.this,
			// getString(R.string.code_empty), false);
			break;

		// 非法条码
		case CODE_ILLEGAL:
			Helper.showSoundToast(SalesSignContentActivity.this,
					getString(R.string.error_code), false);
			break;
		// 成功条码
		case CODE_WAY_BILL:

			ret = true;
			break;
		default:
			break;
		}

		return ret;
	}

	/**
	 * 非法符号判断(只能字母,数字,中文)
	 * 
	 * @param content
	 * @return
	 */
	private boolean isChineseChar(String content) {
		Pattern p = Pattern.compile("^[\\w\\u4e00-\\u9fa5]+$");
		Matcher m = p.matcher(content);
		return m.matches();
	}

	private int Chineselength(String value) {
		int valueLength = 0;
		String chinese = "[\u0391-\uFFE5]";
		/* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
		for (int i = 0; i < value.length(); i++) {
			/* 获取一个字符 */
			String temp = value.substring(i, i + 1);
			/* 判断是否为中文字符 */
			if (temp.matches(chinese)) {
				/* 中文字符长度为2 */
				valueLength += 2;
			} else {
				/* 其他字符长度为1 */
				valueLength += 1;
			}
		}
		return valueLength;
	}

	/**
	 * 扫描数据处理
	 */
	@SuppressLint("NewApi")
	private void processScanData() {
		try {

			if (autograph.getText().toString() == null
					|| autograph.getText().toString().length() == 0) {
				Helper.showSoundToast(this, "签名不能为空!", false);
				return;
			}
			if (Chineselength(autograph.getText().toString()) > 14) {
				Helper.showSoundToast(this, "签名过长,请减少签名长度!", false);
				autograph.setText("");
				autograph.requestFocus();
				// autograph.setSelection(autograph.length());
				// autograph.requestFocus();
				return;
			}
			if (!isChineseChar(autograph.getText().toString())) {
				Helper.showSoundToast(this, "签名不能包含非法字符!", false);
				autograph.setText("");
				autograph.requestFocus();
				return;
			}
			if (!code.getText().toString().isEmpty()
					&& !(autograph.getText().toString().isEmpty())// &&
																	// (signName.equals(autograph.getText().toString()))
			) {

				//Add by wj过滤单号
				boolean isFilter= BillFilterUtil.isFilter(code.getText().toString().trim(),this);
				if(isFilter){
					showFilterDialog(code.getText().toString().trim());
					return;
				}
				//End by wj

				//代收货款校验
				int onOff=StoFilePreference.getInstance(this).getPayMentOnOff();
				if(1==onOff){
					String bill=code.getText().toString().trim();
					if("11".equals(bill.substring(0,2)) || "33".equals(bill.substring(0,2))){
						new HelpGetPaymentThread(bill,SalesSignContentActivity.this,mHandler).start();
					}
				}
				//代收货款校验

				if (addPieceRecord()) {
					this.addCodeNumber();
					setSaveData(true);
					// SoundManager.getInstance(this).playSuccessSound();
					Helper.showSoundAndVibrator(this, true);
					addScanRecordInfo(code.getText().toString());
					// ticketNumber.setText(String.valueOf(++count));
					code.setSelection(code.length());
					// 单票签收
					if (title == R.string.one_sign) {
						autograph.setText("");
						autograph.requestFocus();

					}
				}
				// 提示插入数据失败
				else {
					Helper.showSoundToast(this,
							getString(R.string.code_repeat), false);
				}
				if (title != R.string.one_sign) {
					ScanOpen();
				}
			} else if (code.getText().toString().isEmpty()) {
				// 提示单号不能为空

			} else if (autograph.getText().toString().isEmpty()) {
				// 提示签名不能为空
				SoundManager.getInstance(this).playFailureSound();
				Helper.showToast(SalesSignContentActivity.this, "签名不能为空");
				autograph.requestFocus();
			} else if (!signName.equals(autograph.getText().toString())) {
				Helper.showSoundToast(this, "请选择正确的签名!", false);
				autograph.requestFocus();
				autograph.setText("");
			}
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("processScanData", e.getMessage());
		}
	}

	/**
	 * 数据保存
	 * 
	 * @return true/成功 or false/失败
	 */
	private boolean addPieceRecord() {
		boolean ret;

		dataBusiness.setCommand_type(EnumTableNames.STATUS_TABLE_SALESMAN_SIGN
				.getOpCode());
		dataBusiness.setBar_code_number(code.getText().toString());

		dataBusiness.setCodeType(getExpType(code.getText().toString()));
		// 签收人
		dataBusiness.setRecv_person(autograph.getText().toString());
		// 网点编号
		dataBusiness.setNet_code(StoFilePreference.getInstance(this)
				.getSiteCode());
		// 工号
		dataBusiness.setJob_number(StoFilePreference.getInstance(this)
				.getUserCode());
		ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
				EnumTableNames.STATUS_TABLE_SALESMAN_SIGN);
		return ret;
	}

	/**
	 * 选择列表返回的结果
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == AUTOGRAPH_RESULT && resultCode == RESULT_OK) {
			GetTableParcel courierEntity = data.getParcelableExtra("Name");
			if (courierEntity != null) {
				autograph.setText(courierEntity.getSelectName());
				autograph.setSelection(autograph.length());
				signName = courierEntity.getSelectName();
				code.requestFocus();
				// if (recvPresonCode.length() > 0)
				// destination.requestFocus();
			}
		} else if (requestCode == AUTOGRAPH_RESULT
				&& resultCode == RESULT_FIRST_USER) {
			// signName = "";
			// autograph.setText("");
			/*
			 * Helper.showSoundToast(this, getString(R.string.undefined),
			 * false);
			 */
			code.requestFocus();
		}

	}

	private void exitShuRuFa() {
		InputMethodManager imm = (InputMethodManager) autograph.getContext()
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
		imm.hideSoftInputFromWindow(autograph.getWindowToken(), 0);
	}

	@Override
	public void onBackPressed() {
		// exitShuRuFa();
		showNotice();
		/*
		 * // 确定退出吗? new AlertDialog.Builder(this) .setTitle(R.string.prompt)
		 * .setMessage(R.string.is_exit) .setPositiveButton(R.string.change, new
		 * DialogInterface.OnClickListener() {
		 * 
		 * @Override public void onClick(DialogInterface dialog, int which) {
		 * 
		 * finish(); } }) .setNegativeButton(R.string.cancel, new
		 * DialogInterface.OnClickListener() {
		 * 
		 * @Override public void onClick(DialogInterface dialog, int which) {
		 * dialog.dismiss(); } }).setCancelable(false).show();
		 */
		// super.onBackPressed();
	}

	@Override
	protected void onDestroy() {
		edit.clear();
		super.onDestroy();
	}

	@Override
	protected void handlerScanData(String scanData) {

		if (scanData != null && !scanData.equals("")) {
			String result = scanData;
			code.setText("");
			code.setText(result);
			code.setSelection(code.length());

			if (CheckScanCode(result)) {
				processScanData();
			}
			code.setText("");
		}

	}
}
